﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace ZYXmeBase.Middleware
{
    public class AuthTokenMiddleware
    {
        private readonly RequestDelegate _next;
        public IConfiguration Configuration { get; }

        public AuthTokenMiddleware(RequestDelegate next,IConfiguration configuration)
        {
            _next = next;
            Configuration = configuration;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var endpoint = context.GetEndpoint();
            if (endpoint != null)
            {
                var authAttribute = endpoint.Metadata.GetMetadata<IAllowAnonymous>();
                if (authAttribute != null)
                {
                    await _next(context);
                    return;
                }
            }

            //尝试从Header中获取Authorization
            if (context.Request.Headers.TryGetValue("Authorization", out var extractedAuthToken))
            {

                //需要先删除Bearer前缀
                var jwt = extractedAuthToken.ToString().Substring("Bearer ".Length);

                var isValidToken = ValidateToken(jwt);
                //验证失败，拒绝请求
                if (!isValidToken)
                {
                    context.Response.StatusCode = 401; //Unauthorized
                    await context.Response.WriteAsync("账号认证失败");
                    return;
                }
                // 验证成功, 解析 Claims 并设置 HttpContext.User
                var handler = new JwtSecurityTokenHandler();
                var jwtSecurityToken = handler.ReadJwtToken(jwt);

                var claims = new ClaimsIdentity(jwtSecurityToken.Claims);
                context.User = new ClaimsPrincipal(claims);
               
            }

            //如果验证成功或没有提供AuthToken，继续到下一个中间件
            await _next(context);
        }


        // 这个方法应当包含对Token的实际验证逻辑，这里只是一个简单示例
        private bool ValidateToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            try
            {
                // 这个方法将验证令牌是否是由你的服务器签发，并且是否未被篡改
                var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (Exception)
            {
                // 在令牌签发者、签名、密钥或生命期无效的情况下，此方法将抛出异常
                return false;
            }

            // 如果上述验证都通过，则令牌有效
            return true;
        }

        private TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))
            };
        }


    }

}
